package com.examsystem.handler;


import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.examsystem.pojo.vo.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.HandlerMethod;

import java.util.HashMap;
import java.util.Map;

/**
 * @author fire'ge
 */
@RestControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(Exception.class)
    @RequestMapping(produces = "application/json;charset=utf-8")
    @ResponseBody
    public String handlerError(Exception ex, HandlerMethod hm) {
        ex.printStackTrace();
        Map<String, Object> map = putExceptionMsg(ex, hm);
        return JSON.toJSONString(Result.fail(500,"请求出现错误",map));
    }

    @ExceptionHandler(TokenExpiredException.class)
    @RequestMapping(produces = "application/json;charset=utf-8")
    @ResponseBody
    public String tokenError(Exception ex, HandlerMethod hm) {
        Map<String, Object> map = putExceptionMsg(ex, hm);
        return JSON.toJSONString(Result.fail(500,"token已过期，应重新获取token",map));
    }

    private Map<String, Object> putExceptionMsg(Exception ex, HandlerMethod hm) {
        Map<String, Object> map = new HashMap<>(5);
        map.put("ErrorClass",hm.getBean().getClass().getName());
        map.put("ErrorMethod",hm.getMethod().getName());
        map.put("detailMsg",ex.getMessage());
        map.put("status",false);
        return map;
    }

}
